﻿using System;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
using System.Collections;
using System.Runtime.InteropServices;

namespace MapServer
{
    public class WebSocket
    {
        public TcpClient tTcpClientM;
        public NetworkStream nNetworkStreamM;
        private Thread tThreadM;

        public TcpClient tTcpClientA;
        public NetworkStream nNetworkStreamA;
        private Thread tThreadA;

        private byte[] SendByte;
        private byte[] bytesM;
        private byte[] bytesA;
        //private static int iLoginFlag = -1;//-1未处理，0登陆成功，1登陆失败

        public static ArrayList alStruGpsDataPass = new ArrayList();
        public  ArrayList alMileageStatistics = new ArrayList();
        STRU_GPS_DATA_PASS stPass = new STRU_GPS_DATA_PASS();

        /// <summary>
        /// GPS数据传输结构
        /// </summary>
        [StructLayout(LayoutKind.Explicit, Size = 60, CharSet = CharSet.Unicode)]
        public class STRU_GPS_DATA_PASS
        {
            /// <summary>
            /// 经度
            /// </summary>
            [FieldOffset(0)]
            public double dJingDu;                  // 经度
            /// <summary>
            /// 纬度
            /// </summary>
            [FieldOffset(8)]
            public double dWeiDu;                   // 纬度
            /// <summary>
            /// 车载唯一号
            /// </summary>
            [FieldOffset(16)]
            public UInt32 uiId;                     // 车载唯一号
            /// <summary>
            /// 里程
            /// </summary>
            [FieldOffset(20)]
            public UInt32 uiLiCheng;                // 里程
            /// <summary>
            /// 速度
            /// </summary>
            [FieldOffset(24)]
            public UInt16 usSuDu;                   // 速度
            /// <summary>
            /// 方向
            /// </summary>
            [FieldOffset(26)]
            public Int16 sFangXiang;                // 方向
            /// <summary>
            /// 定时发送时间
            /// </summary>
            [FieldOffset(28)]
            public UInt16 usDingShiFaSongShiJian;   // 定时发送时间
            /// <summary>
            /// 返回指令
            /// </summary>
            [FieldOffset(30)]
            public byte bFanHuiZhiLing;             // 返回指令
            /// <summary>
            /// 经度标志
            /// </summary>
            [FieldOffset(31)]
            public byte bJingDuBiaoZhi;             // 经度标志
            /// <summary>
            /// 纬度标志
            /// </summary>
            [FieldOffset(32)]
            public byte bWeiDuBiaoZhi;              // 纬度标志
            /// <summary>
            /// 定位标志,GPS状态,电源状态,协议标志
            /// </summary>
            [FieldOffset(33)]
            public byte bState1;                    // 定位标志,GPS状态,电源状态,协议标志
            /// <summary>
            /// 车辆部件状态
            /// </summary>
            [FieldOffset(34)]
            public byte bCheLiangBuJianState;       // 车辆部件状态
            /// <summary>
            /// 报警状态
            /// </summary>
            [FieldOffset(35)]
            public byte bBaoJingState;              // 报警状态
            /// <summary>
            /// GPRS状态,信号强度
            /// </summary>
            [FieldOffset(36)]
            public byte bGprsXinHao;                // GPRS状态,信号强度
            /// <summary>
            /// 外设状态
            /// </summary>
            [FieldOffset(37)]
            public byte bWaiSheState;               // 外设状态
            /// <summary>
            /// 停车设置时间
            /// </summary>
            [FieldOffset(38)]
            public byte bTingCheSheZhiShiJian;      // 停车设置时间
            /// <summary>
            /// 超速设置时间
            /// </summary>
            [FieldOffset(39)]
            public byte bChaoSuSheZhiShiJian;       // 超速设置时间
            /// <summary>
            /// 电子围栏设置个数
            /// </summary>
            [FieldOffset(40)]
            public byte bDianZiWeiLanGeShu;         // 电子围栏设置个数
            /// <summary>
            /// 登签
            /// </summary>
            [FieldOffset(41)]
            public byte bDengQian;                  // 登签
            /// <summary>
            /// 定时发送图片的时间
            /// </summary>
            [FieldOffset(42)]
            public byte bFaSongTuPianShiJian;       // 定时发送图片的时间
            /// <summary>
            /// 中心下发的主命令
            /// </summary>
            [FieldOffset(43)]
            public byte bZhongXinXiaFaMingLing;     // 中心下发的主命令
            /// <summary>
            /// 时间
            /// </summary>
            [FieldOffset(44)]
            public DateTime dtShiJian;              // 时间
            ///// <summary>
            ///// 车辆编号
            ///// </summary>
            //[FieldOffset(48)] 
            //public Int32 Id;
            
        }
        public struct sGpsData
        {
            /// <summary>
            /// 经度
            /// </summary>
            public double dJingDu;                  // 经度
            /// <summary>
            /// 纬度
            /// </summary>
            public double dWeiDu;                   // 纬度
            /// <summary>
            /// 车载唯一号
            /// </summary>
            public UInt32 uiId;                     // 车载唯一号
            /// <summary>
            /// 里程
            /// </summary>
            public UInt32 uiLiCheng;                // 里程
            /// <summary>
            /// 速度
            /// </summary>
            public UInt16 usSuDu;                   // 速度
            /// <summary>
            /// 方向
            /// </summary>
            public Int16 sFangXiang;                // 方向
            /// <summary>
            /// 定时发送时间
            /// </summary>
            public UInt16 usDingShiFaSongShiJian;   // 定时发送时间
            /// <summary>
            /// 返回指令
            /// </summary>
            public byte bFanHuiZhiLing;             // 返回指令
            /// <summary>
            /// 经度标志
            /// </summary>
            public byte bJingDuBiaoZhi;             // 经度标志
            /// <summary>
            /// 纬度标志
            /// </summary>
            public byte bWeiDuBiaoZhi;              // 纬度标志
            /// <summary>
            /// 定位标志,GPS状态,电源状态,协议标志
            /// </summary>
            public byte bState1;                    // 定位标志,GPS状态,电源状态,协议标志
            /// <summary>
            /// 车辆部件状态
            /// </summary>
            public byte bCheLiangBuJianState;       // 车辆部件状态
            /// <summary>
            /// 报警状态
            /// </summary>
            public byte bBaoJingState;              // 报警状态
            /// <summary>
            /// GPRS状态,信号强度
            /// </summary>
            public byte bGprsXinHao;                // GPRS状态,信号强度
            /// <summary>
            /// 外设状态
            /// </summary>
            public byte bWaiSheState;               // 外设状态
            /// <summary>
            /// 停车设置时间
            /// </summary>
            public byte bTingCheSheZhiShiJian;      // 停车设置时间
            /// <summary>
            /// 超速设置时间
            /// </summary>
            public byte bChaoSuSheZhiShiJian;       // 超速设置时间
            /// <summary>
            /// 电子围栏设置个数
            /// </summary>
            public byte bDianZiWeiLanGeShu;         // 电子围栏设置个数
            /// <summary>
            /// 登签
            /// </summary>
            public byte bDengQian;                  // 登签
            /// <summary>
            /// 定时发送图片的时间
            /// </summary>
            public byte bFaSongTuPianShiJian;       // 定时发送图片的时间
            /// <summary>
            /// 中心下发的主命令
            /// </summary>
            public byte bZhongXinXiaFaMingLing;     // 中心下发的主命令
            /// <summary>
            /// Gps时间
            /// </summary>
            public DateTime dtShiJian;              // GPS时间
            /// <summary>
            /// 系统时间
            /// </summary>
            public String sSystemShiJian;              //系统时间
            /// <summary>
            /// 车辆编号
            /// </summary>
            public Int32 Id;
            /// <summary>
            /// 操作类型
            /// </summary>
            public Int32 iType;//1-8881端口M-线程，2-8890端口 A-线程
        }
        public bool CreateCreateConnectionTongXun(String sUserName,String sPassWord,String sServerTongXun )
        {
            try
            {
                String []sIpPort = sServerTongXun.Split(',');
                String sIp = sIpPort[0];
                Int32 iPort = Convert.ToInt32( sIpPort[1] );

                tTcpClientM = new TcpClient(sIp, iPort);
                nNetworkStreamM = tTcpClientM.GetStream();

                SendLogin(sUserName, sPassWord);

                // 创建线程对象。这不会启动该线程。
                tThreadM = new Thread(new ThreadStart(ClientTheadM));
                nNetworkStreamM = tTcpClientM.GetStream();
                StartThread( tThreadM );
                return true;
            }
            catch 
            {
                return false;
            }
        }

        public bool CreateCreateConnectionDataBase(String sUserName, String sPassWord, String sServerDataBase)
        {
            try
            {
                String[] sIpPort = sServerDataBase.Split(',');
                String sIp = sIpPort[0];
                Int32 iPort = Convert.ToInt32(sIpPort[1]);
                tTcpClientA = new TcpClient(sIp, iPort);
                nNetworkStreamA = tTcpClientA.GetStream();

                SendLoginA(sUserName, sPassWord);

                // 创建线程对象。这不会启动该线程。
                tThreadA = new Thread(new ThreadStart(ClientTheadA));
                nNetworkStreamA = tTcpClientA.GetStream();
                StartThread( tThreadA );
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool CloseConnectionM()
        {
            try
            {
                EndThread( tThreadM );
                nNetworkStreamM.Close();
                nNetworkStreamM.Dispose();

                tTcpClientM.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }
        public bool CloseConnectionA()
        {
            try
            {
                EndThread(tThreadA);
                nNetworkStreamA.Close();
                nNetworkStreamA.Dispose();

                tTcpClientA.Close();
            }
            catch
            {
                return false;
            }
            return true;

        }
        private void EndThread( Thread tTd )
        {
            // 启动辅助线程。
            tTd.Abort();
        }
        private void StartThread( Thread tTd )
        {
            // 启动辅助线程。
            tTd.Start();
        }
        private void SuspendThread( Thread tTd )
        {
            //挂起线程
            tTd.Suspend();
        }
        private void ClientTheadA()
        {
            ReadDataA();
        }
        private void ClientTheadM()
        {
           //Connection();
           ReadDataM();
        }
        private void ReadDataA()
        {
            bytesA = new byte[102400];

            String strBuf = null, str = null;
            int i, iIndex;
            UInt16 usDataLen = 0;
            bool bState = false;
            try
            {
                while ((i = nNetworkStreamA.Read(bytesA, 0, bytesA.Length)) != 0)
                {
                    strBuf += CPublic.FunBytesToStr(bytesA, 0, i);
                    if (bState)
                    {
                        if (strBuf.Length >= usDataLen)
                        {
                            //内容已接收完
                            str = strBuf.Substring(0, usDataLen);

                            lock (this)
                            {
                                ProcessData(str,2);
                                //m_qZhenTing.Enqueue(str);
                            }
                            //m_areZhenTing[0].Set();

                            strBuf = strBuf.Substring(usDataLen);
                            bState = false;
                        }
                        else
                        {
                            // 内容未接收完
                            continue;
                        }
                    }
                    // 不是取内容状态(还没看到起始标志)
                    while (true)
                    {
                        // 查找起始标志
                        iIndex = strBuf.IndexOf('\xfdfe');
                        if (iIndex > -1)
                        {
                            // 有起始标志字符(但未确定是否真正的起始标志)
                            if (strBuf.Length > (iIndex + 2))
                            {
                                if ((strBuf[iIndex] ^ strBuf[iIndex + 1]) == strBuf[iIndex + 2])
                                {
                                    // 进入取内容状态
                                    usDataLen = strBuf[iIndex + 1];

                                    if (strBuf.Length >= (usDataLen + iIndex + 3))
                                    {
                                        // 内容已接收完
                                        str = strBuf.Substring(iIndex + 3, usDataLen);
                                        // UPDATE BY WZH CMP08082700 BEGIN
                                        /*// 创建线程对象,这不会启动该线程
                                        Thread processThread = new Thread(new ParameterizedThreadStart(ProcessThead));

                                        // 启动处理线程。
                                        processThread.Start(str);*/
                                        // 把数据放入队列
                                        lock (this)
                                        {
                                            ProcessData(str,2);
                                        }
                                        //m_areZhenTing[0].Set();
                                        // UPDATE BY WZH CMP08082700 END

                                        // 继续检测
                                        strBuf = strBuf.Substring(usDataLen + iIndex + 3);
                                        continue;
                                    }
                                    else
                                    {
                                        // 内容未接收完
                                        bState = true;
                                        strBuf = strBuf.Substring(iIndex + 3);
                                        break;
                                    }
                                }
                                else
                                {
                                    // 起始标志字符非法(跳过并进行下一拨检测)
                                    strBuf = strBuf.Substring(iIndex + 1);
                                    continue;
                                }
                            }
                            else
                            {
                                // 还未接收到长度和校验码
                                break;
                            }
                        }
                        else
                        {
                            // 没有起始标志
                            strBuf = null;
                            break;
                        }
                    }
                }
                // 关闭连接
                nNetworkStreamA.Close();
                tTcpClientA.Close();
            }
            catch (ArgumentNullException ee)
            {
                // 关闭连接
                nNetworkStreamA.Close();
                tTcpClientA.Close();
            }
            finally
            {
                // 修改状态栏
                str = "未连接";
                //this.statusStripMain.BeginInvoke(new de_FunIntString(UpdateStatus), new object[] { 1, str });
                nNetworkStreamA = null;
                //if (m_FormDenglu.Visible)
                //    MessageBox.Show("登陆失败\r\n\r\n请确认通讯服务器是否能连接上，用户名和密码是否正确\r\nIP地址和端口号是否设置正确", "警告");
            }
        }
        private void ReadDataM()
        {
            bytesM = new byte[102400];
            String strBuf = null, str = null;
            int i, iIndex;
            UInt16 usDataLen = 0;
            bool bState = false;
            try
            {
                while ((i = nNetworkStreamM.Read(bytesM, 0, bytesM.Length)) != 0)
                {
                    strBuf += CPublic.FunBytesToStr(bytesM, 0, i);
                    if (bState)
                    {
                        if (strBuf.Length >= usDataLen)
                        {
                            //内容已接收完
                            str = strBuf.Substring(0, usDataLen);

                            lock (this)
                            {
                                ProcessData(str,1);
                                //m_qZhenTing.Enqueue(str);
                            }
                            //m_areZhenTing[0].Set();
                          
                            strBuf = strBuf.Substring(usDataLen);
                            bState = false;
                        }
                        else
                        {
                            // 内容未接收完
                            continue;
                        }
                    }
                        // 不是取内容状态(还没看到起始标志)
                    while (true)
                    {
                        // 查找起始标志
                        iIndex = strBuf.IndexOf('\xfdfe');
                        if (iIndex > -1)
                        {
                            // 有起始标志字符(但未确定是否真正的起始标志)
                            if (strBuf.Length > (iIndex + 2))
                            {
                                if ((strBuf[iIndex] ^ strBuf[iIndex + 1]) == strBuf[iIndex + 2])
                                {
                                    // 进入取内容状态
                                    usDataLen = strBuf[iIndex + 1];

                                    if (strBuf.Length >= (usDataLen + iIndex + 3))
                                    {
                                        // 内容已接收完
                                        str = strBuf.Substring(iIndex + 3, usDataLen);
                                        // UPDATE BY WZH CMP08082700 BEGIN
                                        /*// 创建线程对象,这不会启动该线程
                                        Thread processThread = new Thread(new ParameterizedThreadStart(ProcessThead));

                                        // 启动处理线程。
                                        processThread.Start(str);*/
                                        // 把数据放入队列
                                        lock (this)
                                        {
                                            ProcessData( str,1 );
                                        }
                                        //m_areZhenTing[0].Set();
                                        // UPDATE BY WZH CMP08082700 END

                                        // 继续检测
                                        strBuf = strBuf.Substring(usDataLen + iIndex + 3);
                                        continue;
                                    }
                                    else
                                    {
                                        // 内容未接收完
                                        bState = true;
                                        strBuf = strBuf.Substring(iIndex + 3);
                                        break;
                                    }
                                }
                                else
                                {
                                    // 起始标志字符非法(跳过并进行下一拨检测)
                                    strBuf = strBuf.Substring(iIndex + 1);
                                    continue;
                                }
                            }
                            else
                            {
                                // 还未接收到长度和校验码
                                break;
                            }
                        }
                        else
                        {
                            // 没有起始标志
                            strBuf = null;
                            break;
                        }
                    }
                }
                    // 关闭连接
                nNetworkStreamM.Close();
                tTcpClientM.Close();
                }
                catch (ArgumentNullException ee)
                {
                    // 关闭连接
                    nNetworkStreamM.Close();
                    tTcpClientM.Close();
                    string sss = ee.Message;
                }
                finally
                {
                    // 修改状态栏
                    str = "未连接";
                    //this.statusStripMain.BeginInvoke(new de_FunIntString(UpdateStatus), new object[] { 1, str });
                    nNetworkStreamM = null;
                    //if (m_FormDenglu.Visible)
                    //MessageBox.Show("登陆失败\r\n\r\n请确认通讯服务器是否能连接上，用户名和密码是否正确\r\nIP地址和端口号是否设置正确", "警告");
                }
        }
        private void ProcessData( String sData,int iType )
        {
            byte[] bByte = CPublic.FunStrToBytes(sData);
            short cmd = BitConverter.ToInt16(bByte,0);
           
            switch (cmd)
            {
                case 0x02:
                    //sState = BitConverter.ToInt16(bByte,2);
                    //if (sState % 2 == 0)
                    //{
                    //    iLoginFlag = 0;
                    //}
                    //else
                    //{
                    //    iLoginFlag = 1;
                    //}
                    break;
                case 0x24:
                   // sState = BitConverter.ToInt16(bByte,2);
                    SaveData(sData, iType);
                    break;
                case 0x4a:
                    SaveDataA(sData, iType);
                    break;
                case 0x4e:                     // 返回里程统计结果
                case 0x53:                     // 返回工作时间统计结果
                    SaveMileage(sData,iType);
                    break;

            }
        }
        private void SaveMileage(String sData, int iType)
        {
            int iId = 0, iLiCheng = 0, iIndex = 1;
            String sBegin = null, sEnd = null;

            if (!CPublic.FunGetInt32(sData, ref iIndex, ref iId))
                return;
            if (!CPublic.FunGetInt32(sData, ref iIndex, ref iLiCheng))
                return;
            if ((sBegin = CPublic.FunGetString(sData, ref iIndex)) == null)
                return;
            if ((sEnd = CPublic.FunGetString(sData, ref iIndex)) == null)
                return;
            sData = iId + "," + iLiCheng + "," + sBegin + "," + sEnd;
            lock (alMileageStatistics)
            {
                alMileageStatistics.Add(sData);
            }

        }
        private void SaveData(String sData, int iType)
        {
            int i = 0, iIndex = 1;
            String strMsg = sData;
            IntPtr intPtr = IntPtr.Zero;

            if (!CPublic.FunGetInt32(strMsg, ref iIndex, ref i))
            {
                return;
            }
            if (strMsg[iIndex] != '\x1')
            {
                return;
            }
            iIndex++;
            int iLen = strMsg.Substring(iIndex).Length;
            intPtr = Marshal.AllocHGlobal(iLen * 2);
            Marshal.Copy(strMsg.ToCharArray(), iIndex, intPtr, iLen);
            Marshal.PtrToStructure(intPtr, stPass);
            Marshal.FreeHGlobal(intPtr);
            intPtr = IntPtr.Zero; 
            //stPass.Id = i;
            sGpsData sGpsDataInfo = new sGpsData();
            sGpsDataInfo.iType = iType;
            sGpsDataInfo.uiId = Convert.ToUInt16(i);
            sGpsDataInfo.Id = i;
            sGpsDataInfo.dJingDu = stPass.dJingDu;
            sGpsDataInfo.dWeiDu = stPass.dWeiDu;
            sGpsDataInfo.usSuDu = stPass.usSuDu;
            sGpsDataInfo.sSystemShiJian = stPass.dtShiJian.ToString();
            sGpsDataInfo.dtShiJian = stPass.dtShiJian;

            FunBeginTongYongThread(sGpsDataInfo);

           // SetGpsDataPass(iType, i, stPass.dJingDu ,stPass.dWeiDu ,stPass.uiLiCheng,stPass.usSuDu,stPass.sFangXiang,stPass.uiId ,stPass.dtShiJian.ToString() ,stPass.dtShiJian);
        }
        private void SaveDataA(String sData,int iType)
        {
            int i = 0, iIndex = 1;
            String strMsg = sData;
            String strTime = null;
            IntPtr intPtr = IntPtr.Zero;

            if (!CPublic.FunGetInt32(strMsg, ref iIndex, ref i))
            {
                return;
            }
            if ((strTime = CPublic.FunGetString(strMsg, ref iIndex)) == null)
            {
                return;
            }
            if (strMsg[iIndex] != '\x1')
            {
                return;
            }
           
            iIndex++;
            int iLen = strMsg.Substring(iIndex).Length;
            intPtr = Marshal.AllocHGlobal(iLen * 2);
            Marshal.Copy(strMsg.ToCharArray(), iIndex, intPtr, iLen);
            Marshal.PtrToStructure(intPtr, stPass);
            Marshal.FreeHGlobal(intPtr);
            intPtr = IntPtr.Zero;
          
            sGpsData sGpsDataInfo = new sGpsData();
            sGpsDataInfo.iType = iType;
            sGpsDataInfo.uiId = Convert.ToUInt16(i);
            sGpsDataInfo.Id = i;
            sGpsDataInfo.dJingDu = stPass.dJingDu;
            sGpsDataInfo.dWeiDu = stPass.dWeiDu;
            sGpsDataInfo.usSuDu = stPass.usSuDu;
            sGpsDataInfo.sSystemShiJian = strTime;
            sGpsDataInfo.dtShiJian = stPass.dtShiJian;
            sGpsDataInfo.bState1 = stPass.bState1;

            FunBeginTongYongThread(sGpsDataInfo);
            // SetGpsDataPass(iType, i, stPass.dJingDu, stPass.dWeiDu, stPass.uiLiCheng, stPass.usSuDu, stPass.sFangXiang, stPass.uiId, strTime, stPass.dtShiJian);
        }
        void FunBeginTongYongThread(Object sGpsDataInfo)
        {
            // 创建线程对象,这不会启动该线程
            Thread processThread = new Thread(new ParameterizedThreadStart(SetGpsDataPass1));

            // 启动处理线程。
            processThread.Start(sGpsDataInfo);
        }
        public void SetGpsDataPass1(Object oGpsDataInfo)
        {
            sGpsData sGpsDataInfo = (sGpsData)oGpsDataInfo;
            lock (alStruGpsDataPass)
            {
                int i = 0;
                foreach (sGpsData c in alStruGpsDataPass)
                {
                    if (c.Id == sGpsDataInfo.Id && c.iType == sGpsDataInfo.iType )
                    {
                        alStruGpsDataPass[i] = sGpsDataInfo;
                        return;
                    }
                    i++;
                }
                alStruGpsDataPass.Add(sGpsDataInfo);
            }

        }
        public void SetGpsDataPass(int iType,int iId, double dLon, double dLat, uint uiLiCheng,ushort usSuDu,short sFangXiang, uint uiId, String sSystemTime, DateTime dDt)
        {
            sGpsData sGpsDataInfo = new sGpsData();
            sGpsDataInfo.iType = iType;
            sGpsDataInfo.dJingDu = dLon;
            sGpsDataInfo.dWeiDu = dLat;
            sGpsDataInfo.uiId = uiId;
            sGpsDataInfo.usSuDu = usSuDu;
            sGpsDataInfo.sSystemShiJian = sSystemTime;
            sGpsDataInfo.dtShiJian = dDt;
            //sGpsDataInfo.bState1 = ;
            
            lock(alStruGpsDataPass)
            {
                int i = 0;
                foreach (sGpsData c in alStruGpsDataPass)
                {
                    if (c.Id == iId && c.iType == iType)
                    {
                        alStruGpsDataPass[i] = sGpsDataInfo;
                        return;
                    }
                    i++;
                }
                alStruGpsDataPass.Add(sGpsDataInfo);
            }
        }
        public sGpsData SelectGpsDataPass(int iId,int iType)
        {
            sGpsData sGps = new sGpsData();
            lock (alStruGpsDataPass)
            {
                foreach (sGpsData c in alStruGpsDataPass)
                {
                    if (c.Id == iId && c.iType == iType)
                    {
                        return c;
                    }
                }
            }
            return sGps;
        }
        public void SendDownFence(int iCheId, String sFenceInfo)
        {
            SendByte = ProtocolPack.DownFencePack(iCheId, sFenceInfo);
            SendMessage(nNetworkStreamM,SendByte,0,SendByte.Length);
        }
        public void SendLocation( int iCheId)
        {
            SendByte = ProtocolPack.LocationPack(iCheId);
            SendMessage( nNetworkStreamM,SendByte,0,SendByte.Length);
        }
        public void SendLastLocation(int iCheId)
        {
            SendByte = ProtocolPack.LastLocationPack(iCheId);
            SendMessage(nNetworkStreamA, SendByte, 0, SendByte.Length);
        }
        public bool SendMileageStatistics(int iCheId, String sStarTime, String sEndTime)
        {
            try
            {
                SendByte = ProtocolPack.MileageStatistics(iCheId, sStarTime, sEndTime);
                SendMessage(nNetworkStreamA, SendByte, 0, SendByte.Length);
                return true;
            }
            catch 
            {
                return false;
            }
        }
        public void SendLogin(  String sUserName,String sPassWord)
        {
            //登陆后台服务器(登陆状态，用户名，密码）
            SendByte = ProtocolPack.UserLoginPack(sUserName, sPassWord);
            SendMessage( nNetworkStreamM, SendByte, 0, SendByte.Length);
        }
        public void SendLoginA(String sUserName, String sPassWord)
        {
            //登陆后台服务器(登陆状态，用户名，密码）
            SendByte = ProtocolPack.UserLoginPack(sUserName, sPassWord);
            SendMessage(nNetworkStreamA, SendByte, 0, SendByte.Length);
        }
        //发送命令的方法
        public void SendMessage( NetworkStream nNs, byte[] buffer, int offset, int size)
        {
            try
            {
                nNs.Write(buffer, offset, size);
            }
            catch (Exception catchmessage)
            {
                string s = catchmessage.ToString();
            }
        }
    }
}